package net.concurrent;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {

	private static ExecutorService service = Executors.newCachedThreadPool();
	//循环等待
	private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

	public static void main(String[] args) {
		service.execute(new TaskCyclic(cyclicBarrier));
		service.execute(new TaskCyclic(cyclicBarrier));
		service.execute(new TaskCyclic(cyclicBarrier));
		
		service.shutdown();
	}
}

class TaskCyclic implements Runnable{
	private CyclicBarrier cyclic = null;
	public TaskCyclic(CyclicBarrier cyclicBarrier){
		this.cyclic = cyclicBarrier;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		try {
			Random random = new Random();
			long ID = Thread.currentThread().getId();
			int n = random.nextInt(1000);
			Thread.sleep(n);
			System.out.println(ID + " 已经完成任务A，用时"+n+"！(此时共有" + (cyclic.getNumberWaiting() + 1) + "已经完成)");
			if(cyclic.getNumberWaiting() == 2){
				System.out.println("任务A最终被完成，继续进行任务B！");
			}
			cyclic.await();
			n = random.nextInt(1000);
			Thread.sleep(n);
			System.out.println(ID + " 已经完成任务B，用时"+n+"！(此时共有" + (cyclic.getNumberWaiting() + 1) + "已经完成)");
			if(cyclic.getNumberWaiting() == 2){
				System.out.println("任务B最终被完成！");
			}
			cyclic.await();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
